package deployment

import (
	"context"
	"fmt"
	v1 "k8s.io/api/apps/v1"
	v13 "k8s.io/api/core/v1"
	v12 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8sapi/lib"
)

type DeploymentRequest struct {
	Name string  `form:"name" binding:"required,min=2"`
	Image string `form:"image" binding:"required,min=5"`
	Ports []int32 `form:"port"`
}
//生成容器配置
func genContainers(req *DeploymentRequest) []v13.Container{
	ret:=make([]v13.Container,1)
	ports:=make([]v13.ContainerPort,len(req.Ports))  //构建端口参数
	for i,_:=range ports{
		ports[i].Name=fmt.Sprintf("%s%d%d",req.Name,req.Ports[i],i)
		ports[i].Protocol="TCP"
		ports[i].ContainerPort=req.Ports[i]
	}
	ret[0]=v13.Container{
		Name:req.Name,
		Image:req.Image,
		Ports:ports,
	}
	return ret
}
//生成标签配置
func genLabels(req *DeploymentRequest) map[string]string{
	return map[string]string{
		"app":req.Name,
	}
}
func CreateDeployment(req *DeploymentRequest) error {
	ns:= "default"
	_,err:=lib.K8sClient.AppsV1().Deployments(ns).
		Create(context.Background(),&v1.Deployment{
			ObjectMeta:v12.ObjectMeta{Name:req.Name,Namespace:ns},
			Spec:v1.DeploymentSpec{
				Selector:&v12.LabelSelector{
					MatchLabels:genLabels(req),
				},
				Template:v13.PodTemplateSpec{
					ObjectMeta:v12.ObjectMeta{
						Labels:genLabels(req),
					},
					Spec:v13.PodSpec{
						Containers:genContainers(req),
					},
				},
			},
	},v12.CreateOptions{})
	return err
}

//删除Deployment
func DelDeployment(ns string ,depname string) error {
	err:=lib.K8sClient.AppsV1().Deployments(ns).
		Delete(context.Background(),depname,v12.DeleteOptions{})
	return err
}

//判断dep是否就绪
func GetDeploymentIsComplete(dep *v1.Deployment) bool {
	return dep.Status.Replicas==dep.Status.AvailableReplicas
}
//获取deployment失败状态
func GetDeploymentCondition(dep *v1.Deployment) string{
	for _,item:=range dep.Status.Conditions{
		if string(item.Type)=="Available" && string(item.Status)!="True"{
			return item.Message
		}
	}
	return ""
}